import {Component, OnInit, ViewChild} from '@angular/core';
import {FileUploadNormalComponent} from '../purchase/file-upload-normal/file-upload-normal.component';
import {ZQService} from './zq.service';
import {ZQListComponent, ZQSearchModel} from './zq-list/zq-list.component';
import {ZQPaymentComponent} from './zq-payment/zq-payment.component';
import {AlterationComponent} from './alteration/alteration.component';
import {ZQListService} from './zq-list/zq-list.service';
import {AppPaginationComponent, PaginationModel} from '../../../widgets/pagination/pagination.component';
import {environment} from '../../../../environments/environment';
import {Util} from "../../../common/util";
import * as moment from 'moment';
import * as _ from 'lodash';

@Component({
  selector: 'new-stock-zq',
  templateUrl: './zq.component.html',
  styleUrls: ['./zq.component.scss'],
  providers: [ZQService, ZQListService]
})
export class ZQComponent implements OnInit {


  public isShowBallot = true;

  // 列表
  public remittanceList: Array<any>;

  // 列表当前页全选标记
  public isCheckedAll = false;

  // 列表类型（1：中签管理，2：已缴款 3：申购中签管理）
  public type = "3";

  // 列表组件
  @ViewChild(ZQListComponent)
  public zQListComponent: ZQListComponent;

  // 选择交易场所模态框
  @ViewChild(ZQPaymentComponent)
  public ZQPaymentComponent: ZQPaymentComponent;

  // 分页配置
  public pageInfo: PaginationModel = {
    currentPageNum: 1,
    totalPages: 1,
    total: 0 // 总记录数
  };

  // 到账状态
  public cDzStatus = {
    "0": "未到账",
    "1": "到账",
    "9": "到账异常（金额不一致）",
    "2": "到账待复核",
    "3": "取消待复核",
    "4": "手工到账"
  };

  // 手工到账操作下允许操作的到账状态集合
  // 例如 02(到账确认复核) 允许 到账状态为 0/9的数据进行操作
  public actionAllow = {
    "02": "0,9",
    "24": "2",
    "20": "2",
    "43": "3",
    "30": "3",
    "34": "4"
  };

  // 分页组件
  @ViewChild(AppPaginationComponent)
  public paginationComponent: AppPaginationComponent;

  // 导入配售对象
  @ViewChild(FileUploadNormalComponent)
  private fileUploadNormalComponent: FileUploadNormalComponent;

  // 导入配售对象
  @ViewChild(AlterationComponent)
  private alterationComponent: AlterationComponent;

  // 文件上传modal配置信息
  public fileUploadModal = {
    modalTile: "", // modal title
    title: "", // titel
    url: "", // url
    method: "", // POST OR GET
    itemAlias: "", // file alias
    formDatas: [] // POST 参数
  };

  constructor(public zQService: ZQService,
              public zQListService: ZQListService) {
  }

  changeBallotStatus() {
    this.isShowBallot = !this.isShowBallot;
  }


  /**
   * [search 查询]
   */
  search() {
    this.zQListComponent.search();
  }

  /**
   * [resetSearch 重置查询条件]
   */
  resetSearch() {
    this.zQListComponent.resetSearch();
  }

  ngOnInit() {
  }

  /**
   * [checkedAll 列表当前页全选]
   */
  checkedAll() {
    if (this.isCheckedAll) { // 更新为全选
      _.forEach(this.remittanceList, item => {
        item.isChecked = true;
      });
    } else { // 更新为不全选
      _.forEach(this.remittanceList, item => {
        item.isChecked = false;
      });
    }
  }

  /**
   * [checked 是否需要更新全选]
   * @param {[type]} remittance [实例对象]
   */
  checked(remittance) {
    if (remittance.isChecked) {
      const temp = _.find(this.remittanceList, {isChecked: false});
      if (!temp) { // 全选重置为 true
        this.isCheckedAll = true;
      }
    } else { // 全选重置为 false
      this.isCheckedAll = false;
    }
  }

  /**
   * [toggleZQModalOpen 导入中签数据]
   */
  toggleZQModalOpen() {
    // 配置导入文件信息
    this.fileUploadModal = {
      modalTile: "导入中签数据",
      title: "请选择上传的中签数据文件",
      url: environment.server + "otc/v1/Newstock/ZQList",
      method: "POST",
      itemAlias: "file",
      formDatas: []
    };

    this.fileUploadNormalComponent.openModal();
  }

  /**
   * [transferMoney 生成划款指令]
   */
  transferMoney() {
    window["$"]("#optionsRadios1").prop("checked", true);
    const remittance = _.filter(this.zQListComponent.remittanceList, {isChecked: true});
    if(this.validateTransfer(remittance)){
      if (remittance.length === 0) {
        this.ZQPaymentComponent.openModal();
      } else {
          // const nowDay = window['moment'](new Date()).format('YYYYMMDD');
          this.ZQPaymentComponent.transferMoney(remittance, null, null);
      }
    }
  }

  // 校验是否符合生成划款指令资格
  validateTransfer(remittance){
    var answer = true;
    remittance.forEach(function(item){
      // 如果有未中签的数据
      if(item.matchResult==="0"){
        window["swal"]("提示", "中签文件未导入，不能生成划款指令", "warning");
        answer = false;
      }
    });
    return answer;
  }

  /**
   * [goHistory 历史交易]
   */
  goHistory() {
    // 重置查询条件
    this.zQListComponent.resetSearch();
    this.zQListComponent.searchBody.isHisData = true;
    const data: ZQSearchModel = {
      isHisData: true
    };
    // 查询历史
    this.zQListComponent.getRemittanceList(data);
  }

  /**
   * [backZq 返回非历史页面]
   */
  backZq() {
    // 重置查询条件
    this.zQListComponent.resetSearch();
    this.zQListComponent.searchBody.isHisData = false;
    const data: ZQSearchModel = {
      isHisData: false
    };
    // 查询历史
    this.zQListComponent.getRemittanceList(data);
  }

  /**
   * [toggleDZModalOpen 到账确认文件]
   */
  toggleDZModalOpen() {
    // 配置导入文件信息
    this.fileUploadModal = {
      modalTile: "导入到账文件",
      title: "请选择上传的到账文件",
      url: environment.server + "otc/v1/Newstock/DZList",
      method: "POST",
      itemAlias: "file",
      formDatas: []
    };

    this.fileUploadNormalComponent.openModal();
  }

  /**
   * 手工到账确认通用函数
   * param [{
	 * 		action: 手工到账操作编号,
   *    $event: 点击的DOM对象
	 * }]
   */
  manualTransferredConfirm(action, $event) {
    const that = this;
    const remittance = _.filter(this.zQListComponent.remittanceList, {isChecked: true});
    if (remittance.length === 0) {
      window["swal"]("提示", "请选择一条数据进行操作！", "info");
    } else {
      // param 查询参数对象
      const param = this.zQListComponent.getDataToTransferredConfirm(remittance, action);
      const validate = that.validateTransferredConfirm(param);
      if(validate.message!==""){
        window["swal"]("提示", validate.message, "warning");
      }
      if(validate.isPass){
        this.zQListService.manualTransferredConfirm(param).subscribe(result => {
          if (result) {
            window["swal"]("提示", `${$event.target.textContent}成功`, "success");
          }
          that.zQListComponent.refleshCurrPage();
        });
      }
    }
  }

  /**
   * 校验数据是否符合手工到账确认资格
   * @param data 需要检测的数据
   */
  validateTransferredConfirm(data){
    const answer = {
      isPass: false,
      message:""
    }
    const action = data.action;
    if(data.length === 0){
      answer.message = "请选择一行数据进行操作！";
      return answer;
    }
    for (let i=0; i<data.cDzStatus.length;i++ ) {
      if(!this.actionAllow[action].includes(data.cDzStatus[i])){
        if(action === "02"){
          answer.message = "只有未到账或到账异常的数据，才能进行到账确认复核操作！";
          return answer;
        }
        if(action === "20"){
          answer.message = "只有到账确认待复核的数据，才能进行驳回到账确认复核操作！";
          return answer;
        }
        if(action === "24"){
          answer.message = "只有到账确认待复核的数据，才能进行通过到账确认复核操作！";
          return answer;
        }
        if(action === "34"){
          answer.message = "只有手工到账的数据，才能进行撤销到账复刻操作！";
          return answer;
        }
        if(action === "43"){
          answer.message = "只有已撤销到账待复核的数据，才能进行通过撤销到账复核操作！";
          return answer;
        }
        if(action === "30"){
          answer.message = "只有已撤销到账待复核的数据，才能进行驳回撤销到账复核操作！";
          return answer;
        }
      }
      if(action === "24"){
        if(data.vcDzUser[i] === sessionStorage.getItem('username')){
          answer.message = "到账确认复核与通过到账确认复核不能是同一个用户操作！";
          return answer;
        }
      }
    }
    if(answer.message === "") {
      answer.isPass = true;
    }
    return answer;
  }

  /**
   * 导出通用方法
   * @param path 请求地址
   * @param method 请求方式
   */
  exportCommonMethod(path, method) {
    const $ = window["$"];
    var param = this.zQListComponent.warpperSearchModule();
    if (method === 'get') {
      var str = ""
      for(let i in param){
        str += "&" + i + "=" + param[i];
      }
      // TODO 下载文件使用iframe的标签，临时解决方案。
      const iframe = $("<iframe id='downloadiframe'>");   // 定义一个iframe
      iframe.attr('style', 'display:none');
      iframe.attr('src', environment.server + path + '?token='+sessionStorage.getItem('username')+ str);
      $('body').append(iframe);  // 将iframe放置在web中
      setTimeout("$('#downloadiframe').remove()", 5000);
    }
    if (method === 'post') {
      window.fetch(`${environment.server}${path}`, {
        method: 'POST',
        headers: {
          'Content-type': 'application/json',
          'token':sessionStorage.getItem('username')
        },
        body: JSON.stringify([param])
      }).then(function (res) {
        console.log(res);
        res.blob().then(function (blob) {
          console.log(res.headers.get('Content-Disposition'));
          var file = new File([blob], '下载附件.xls', { type: blob.type });
          var a = document.createElement('a');
          var url = window.URL.createObjectURL(blob);
          a.href = url;
          a.download = file.name;
          a.click();
          window.URL.revokeObjectURL(url);
        });
      });
    }
  }

  /**
   * [toggleAlterationModalOpen 变更匹配]
   */
  toggleAlterationModalOpen() {
    const remittance = _.filter(this.zQListComponent.remittanceList, {isChecked: true});

    if (remittance.length === 0) { // 没有选择证劵
      window["swal"]("提示", "请选择一个变更匹配的证劵", "info");
    } else if (remittance.length === 1) { // 选择一笔证劵
      // 初始化变更匹配 modal 页面数据
      this.alterationComponent.init(remittance[0]);
      this.alterationComponent.openModal();
    } else if (remittance.length > 1) { // 选择了多比证劵
      window["swal"]("提示", "请选择一个变更匹配的证劵!", "warning");
    }
  }

  /**
   * [markZQHandle 标记中签]
   * @param zqFlag 标记中签/撤销标记未中签
   * @param $event 点击的DOM对象
   */
  markZQHandle(zqFlag, $event) {
    const that = this;
    const remittance = _.filter(that.zQListComponent.remittanceList, {isChecked: true});

    if (remittance.length === 0) {
      window["swal"]("提示", "请选择一条数据进行操作", "info");
    } else {
      // param 查询参数对象
      const param = that.zQListComponent.getDataToMarkZQHandle(remittance, zqFlag);
      // 如果是标记未中签操作
      if (zqFlag === '0') {
        // 遍历查询参数对象，判断matchResult（指令及中签比对）是否是未中签，如果不是不允许操作.
        for (let i = 0; i < param.matchResult.length; i++) {
          if (param.matchResult[i] !== '0') {
            window["swal"]("提示", `只有未中签的数据才能进行${$event.target.textContent}操作！`, "warning");
            return false;
          }
        }
      }
      // 如果是撤销标记未中签操作
      if (zqFlag !== '0') {
        for (let i = 0; i < param.matchResult.length; i++) {
          if (param.matchResult[i] === '0') {
            window["swal"]("提示", `只有标记未中签的数据才能进行${$event.target.textContent}操作！`, "warning");
            return false;
          }
        }
      }
      that.zQListService.markZQHandle(param).subscribe(result => {
        if (result) {
          window["swal"]("提示", `${$event.target.textContent}成功`, "success");
          that.zQListComponent.refleshCurrPage();
        }
      });
    }
  }

  /**
   * [refleshCurrPage 刷新当前列表]
   * @param {[type]} event [description]
   */
  refleshCurrPage(event) {
    if (event) {
      this.zQListComponent.refleshCurrPage();
    }
  }

  /**
   * [reflesh 刷新]
   */
  reflesh(event?) {
    this.zQListComponent.resetSearch();
  }

  /**
   * [toggleWDModalOpen 导入万德文件]
   */
  toggleWDModalOpen() {
    // 配置导入文件信息
    this.fileUploadModal = {
      modalTile: "导入万德文件",
      title: "请选择上传的万德中签文件",
      url: environment.server + "otc/v1/Newstock/windZQ",
      method: "POST",
      itemAlias: "file",
      formDatas: []
    };

    this.fileUploadNormalComponent.openModal();
  }
}
